#include "flagHandle.h"

static LinkedListStruct* linkedList_listeners = NULL;

void flagHandle_init(void) {
  mempool_init(0x400);
  if (linkedList_listeners == NULL) {
    linkedList_listeners = linkedList_new();
  }
}
static FlagHandleStruct* flagHandle_find(uint16_t index) {
  FlagHandleStruct* listener;

  linkedList_listeners->current = linkedList_listeners->first;
  while (linkedList_listeners->current != NULL) {
    listener = (FlagHandleStruct*)linkedList_listeners->current->data;
    if (listener->index == index) {
      return listener;
    }
    linkedList_listeners->current = linkedList_listeners->current->next;
  }
  return NULL;
}
void flagHandle_addListener(uint16_t index, void* fun) {
  FlagHandleStruct* listener;
  listener = flagHandle_find(index);
  if (listener == NULL) {
    listener = (FlagHandleStruct*)mempool_alloc(sizeof(FlagHandleStruct));
    listener->index = index;
  }
  listener->status = flagHandleStatus_ready;
  listener->fun = fun;

  linkedList_addData(linkedList_listeners, listener);
}
void flagHandle_delListener(uint16_t index) {
  FlagHandleStruct* listener = flagHandle_find(index);
  linkedList_delData(linkedList_listeners, NULL);
  mempool_free(listener);
}
void flagHandle_solve(void) {
  FlagHandleStruct* listener;
  LinkedListUnitStruct* current;

  current = linkedList_listeners->first;
  while (current != NULL) {
    listener = (FlagHandleStruct*)current->data;
    if (listener->status == flagHandleStatus_run) {
      typedef void(FUN)(void* args);
      FUN* fun = (FUN*)listener->fun;
      if (fun)
        fun(listener->args);
      listener->status = flagHandleStatus_finish;
    }
    current = current->next;
  }
}
void flagHandle_setFlag(uint16_t index, void* args) {
  FlagHandleStruct* listener = flagHandle_find(index);
  listener->status = flagHandleStatus_run;
  listener->args = args;
}
void flagHandle_resetFlag(uint16_t index) {
  FlagHandleStruct* listener = flagHandle_find(index);
  listener->status = flagHandleStatus_finish;
}
